from rest_framework import serializers
from apps.UMM.models import User
import logging

logger = logging.getLogger(__name__)


class UserListSerializer(serializers.ModelSerializer):
    """用户列表序列化器"""
    role_display = serializers.CharField(source='get_role_display', read_only=True)
    
    class Meta:
        model = User
        fields = ['id', 'username', 'nickname', 'phone_number', 'email', 'role', 'role_display', 'employee_id']
        read_only_fields = ['id']


class UserSerializer(serializers.ModelSerializer):
    """用户详情序列化器"""
    role_display = serializers.CharField(source='get_role_display', read_only=True)
    
    class Meta:
        model = User
        fields = ['id', 'username', 'nickname', 'phone_number', 'email', 'role', 'role_display', 'pwd', 'employee_id']
        read_only_fields = ['id']
        extra_kwargs = {
            'pwd': {'write_only': True, 'required': False}
        }
    
    def validate(self, data):
        """验证数据"""
        logger.info(f"用户序列化器验证数据: {data}")
        
        # 创建新用户时，密码是必填的
        if self.instance is None and 'pwd' not in data:
            raise serializers.ValidationError({"pwd": "创建用户时密码不能为空"})
            
        return data
        
    def create(self, validated_data):
        """创建用户"""
        logger.info(f"创建用户: {validated_data}")
        user = User.objects.create(**validated_data)
        return user
    
    def update(self, instance, validated_data):
        """更新用户信息"""
        logger.info(f"更新用户 {instance.id}: {validated_data}")
        
        # 记录更新前的值
        original_values = {
            'username': instance.username,
            'nickname': instance.nickname,
            'email': instance.email,
            'phone_number': instance.phone_number,
            'role': instance.role
        }
        
        # 更新值
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        
        # 记录变更的字段
        changes = {}
        for field, orig_value in original_values.items():
            new_value = getattr(instance, field)
            if orig_value != new_value:
                changes[field] = {'from': orig_value, 'to': new_value}
        
        if changes:
            logger.info(f"用户 {instance.id} 更新的字段: {changes}")
        
        instance.save()
        logger.info(f"用户 {instance.id} 更新成功")
        return instance 